<?php 


$wx=new weiXin();

$wx->checkSignature();

$wx->getMsg();

class weiXin{

    public function getMsg()
    {

        $postxml = file_get_contents('php://input');//读取 POST 的原始数据
        
        $data = simplexml_load_string($postxml, 'SimpleXMLElement', LIBXML_NOCDATA);//解析xml,解析后为对象格式l
       
        $json=file_get_contents("xiaoxi.json");

        if($json!==''){

            $arr=json_decode($json,true);

            var_dump($arr);

            array_push($arr, $data);

            $jsonData=json_encode($arr,JSON_UNESCAPED_UNICODE);

            file_put_contents('xiaoxi.json', $jsonData);

        }else{


            $arr=array();

            array_push($arr, $data);

            $jsonData=json_encode($arr,JSON_UNESCAPED_UNICODE);

            file_put_contents('xiaoxi.json', $jsonData);



        }

        $fromUsername = $data->FromUserName; //获取发送方帐号（OpenID）
        $toUsername = $data->ToUserName; //获取接收方账号
        $keyword = trim($data->Content); //获取消息内容
        $masType = $data->MsgType;//获取消息类型，可以作分类判断。本例默认是文本消息，不做判断
        $time = time(); //获取当前时间戳

        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            <FuncFlag>0</FuncFlag>
            </xml>"; 

        $msgType = "text"; //消息类型
        $contentStr = '您发送的是'.$keyword;
        $resultStr = sprintf($textTpl,$fromUsername,$toUsername,$time,$msgType,$contentStr);

        echo $resultStr;

       // echo 'success';
        


    }

    public function checkSignature() //连接服务器验证用的
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $echostr = $_GET["echostr"];
        
        $token = 'asd123456zxc';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
           echo $echostr;
    }

}



}


 ?>


